package com.jagochan.module.rbac.sys_user_role.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jagochan.module.rbac.sys_user_role.domain.SysUserRole;
import com.jagochan.module.rbac.sys_user_role.mapper.SysUserRoleMapper;
import com.jagochan.module.rbac.sys_user_role.service.SysUserRoleService;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class SysUserRoleServiceImpl extends ServiceImpl<SysUserRoleMapper, SysUserRole> implements SysUserRoleService {
    /**
     * 保存用户角色关系
     *
     * @param userId 用户ID
     * @param roleId 角色ID字符串（用【,】分隔）
     */
    @Override
    public boolean save(Long userId, String roleId) {
        if (StringUtils.isEmpty(roleId)) return false;

        String[] roleIdStrArr = roleId.split(",");
        List<SysUserRole> userRoleList = Arrays.stream(roleIdStrArr).map(roleIdStr -> {
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setUserId(userId);
            sysUserRole.setRoleId(Long.valueOf(roleIdStr));
            return sysUserRole;
        }).collect(Collectors.toList());

        return saveBatch(userRoleList);
    }

    @Override
    public void removeByUserId(Long userId) {
        LambdaQueryWrapper<SysUserRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUserRole::getUserId, userId);
        remove(wrapper);
    }

    /**
     * 根据用户ID查询用户的角色ID列表
     */
    @Override
    public List<Long> listRoleIdsByUserId(Long userId) {
        List<SysUserRole> list = lambdaQuery().eq(SysUserRole::getUserId, userId)
                .select(SysUserRole::getRoleId).list();
        if (Objects.isNull(list) || list.isEmpty()) return Collections.emptyList();
        return list.stream().map(SysUserRole::getRoleId).collect(Collectors.toList());
    }
}